﻿<template>
  <a-drawer
    :title="title"
    width="90%"
    :visible="visible"
    @close="
      () => {
        this.visible = false
      }
    "
  >
    <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="价格表名称" prop="ListName">
            <a-input v-model="entity.ListName" autocomplete="off" placeholder="价格表名称" />
          </a-form-model-item>
        </a-col>

        <a-col :span="8">
          <a-form-model-item label="有效期开始时间" prop="StartValidity">
            <a-date-picker format="YYYY-MM-DD" style="width: 100%" v-model="entity.StartValidity" />
            <!-- <a-input v-model="entity.StartValidity" autocomplete="off" placeholder="有效期开始时间" /> -->
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="有效期结束时间" prop="EndValidity">
            <a-date-picker
              :disabled-date="disabledDate"
              format="YYYY-MM-DD"
              style="width: 100%"
              v-model="entity.EndValidity"
            />
            <!-- <a-input v-model="entity.EndValidity" autocomplete="off" placeholder="有效期结束时间" /> -->
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="备注" prop="Remark">
            <a-textarea v-model="entity.Remark" autocomplete="off" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="是否采用阶梯价" prop="IsLadderPrice">
            <a-radio-group v-model="entity.IsLadderPrice" :default-value="false" button-style="solid">
              <a-radio-button :value="true"> 是 </a-radio-button>
              <a-radio-button :value="false"> 否 </a-radio-button>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <!-- <a-col :span="8">
          <a-form-model-item label="状态" prop="State">
            <a-input v-model="entity.State" autocomplete="off" placeholder="状态" />
          </a-form-model-item>
        </a-col> -->
      </a-row>
    </a-form-model>
    <a-table
      class="tables"
      ref="table"
      :scroll="{ y: 460 }"
      :columns="columns"
      :rowKey="(row, index) => row.cInvCode"
      :dataSource="data"
      :pagination="pagination"
      @change="handleTableChange"
      :bordered="true"
      size="small"
    >
      <template slot="cInvName" slot-scope="text, record">
        <span>{{ record.cInvCode }}/{{ record.cInvName }}</span>
      </template>

      <span slot="action" slot-scope="text, record, index">
        <template>
          <!-- <a @click="handleEdit(record.Id)">编辑</a>
          <a-divider type="vertical" /> -->
          <a v-if="hasPerm('Quot_PriceListDetails.Delete')" @click="handleDelete([record.Id], index)">删除</a>
        </template>
      </span>

      <template slot="StandardPrice" slot-scope="text, record">
        <a-input
          style="text-align: right;"
          size="small"
          class="input"
          type="number"
          v-model="record.StandardPrice"
        ></a-input>
      </template>
      <template slot="MinimumDiscount" slot-scope="text, record">
        <a-input
          style="text-align: right;"
          size="small"
          class="input"
          type="number"
          v-model="record.MinimumDiscount"
        ></a-input>
      </template>
      <template slot="LowerLimitPrice1" slot-scope="text, record">
        <a-input
          size="small"
          style="text-align: right;"
          class="input"
          type="number"
          @blur="blur1($event, record)"
          v-model="record.LowerLimitPrice1"
        ></a-input>
      </template>
      <template slot="LowerLimitPrice2" slot-scope="text, record">
        <a-input
          size="small"
          @blur="blur2($event, record)"
          style="text-align: right;"
          class="input"
          type="number"
          v-model="record.LowerLimitPrice2"
        ></a-input>
      </template>
      <template slot="LowerLimitPrice3" slot-scope="text, record">
        <a-input
          size="small"
          @blur="blur3($event, record)"
          style="text-align: right;"
          class="input"
          type="number"
          v-model="record.LowerLimitPrice3"
        ></a-input>
      </template>
      <template slot="NumLowerLimit1" slot-scope="text, record">
        <a-input
          style="text-align: right;"
          size="small"
          class="input"
          placeholder="请输入N1的值"
          type="number"
          v-model="record.NumLowerLimit1"
        ></a-input>
      </template>
      <template slot="NumLowerLimit2" slot-scope="text, record">
        <a-input
          style="text-align: right;"
          size="small"
          class="input"
          placeholder="请输入N2的值"
          type="number"
          v-model="record.NumLowerLimit2"
        ></a-input>
      </template>
      <template slot="aid" slot-scope="text, record, index">
        <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
      </template>
      <template slot="NumLowerLimit3" slot-scope="text, record">
        <a-input
          style="text-align: right;"
          size="small"
          class="input"
          placeholder="请输入N3的值"
          type="number"
          v-model="record.NumLowerLimit3"
        ></a-input>
      </template>
    </a-table>
    <MaterialChoose ref="materialChoose" @onChoose="handleChoose"></MaterialChoose>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <a-button type="primary" @click="addTable">添加</a-button>&nbsp; <a-button @click="close">取消</a-button>&nbsp;
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import MaterialChoose from '@/components/MaterialChoose/MaterialChooseCopy1.vue'
import moment from 'moment'
const columns = [
  {
    title: '序号',
    dataIndex: 'aid',
    align: 'center',
    scopedSlots: { customRender: 'aid' },
    width: '50px'
  },
  { title: '品名', dataIndex: 'cInvName', scopedSlots: { customRender: 'cInvName' }, width: '20%' },
  { title: '标准价格', dataIndex: 'StandardPrice', scopedSlots: { customRender: 'StandardPrice' } },
  {
    title: '最低折扣',
    dataIndex: 'MinimumDiscount',
    align: 'center',
    scopedSlots: { customRender: 'MinimumDiscount' }
  },

  {
    title: '0-N1数量',
    dataIndex: 'NumLowerLimit1',
    align: 'center',
    scopedSlots: { customRender: 'NumLowerLimit1' }
  },
  {
    title: 'N1-N2价格',
    dataIndex: 'LowerLimitPrice1',
    align: 'center',
    scopedSlots: { customRender: 'LowerLimitPrice1' }
  },

  {
    title: 'N1-N2数量',
    dataIndex: 'NumLowerLimit2',
    align: 'center',
    scopedSlots: { customRender: 'NumLowerLimit2' }
  },
  {
    title: 'N2-N3价格',
    dataIndex: 'LowerLimitPrice2',
    align: 'center',
    scopedSlots: { customRender: 'LowerLimitPrice2' }
  },

  {
    title: 'N2-N3数量',
    dataIndex: 'NumLowerLimit3',
    align: 'center',
    scopedSlots: { customRender: 'NumLowerLimit3' }
  },
  {
    title: '大于N3价格',
    dataIndex: 'LowerLimitPrice3',
    align: 'center',
    scopedSlots: { customRender: 'LowerLimitPrice3' }
  },

  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' } }
]

export default {
  props: {
    parentObj: Object
  },
  components: {
    MaterialChoose
  },
  watch: {
    data: {
      handler(n, o) {
        //console.log(n)
        n.forEach(item => {
          if (Number(item.StandardPrice) < 0) {
            this.$set(item, 'StandardPrice', 1)
            this.$message.warning('不能小于0')
            return
          }
          if (Number(item.MinimumDiscount) < 0) {
            this.$set(item, 'MinimumDiscount', 1)
            this.$message.warning('不能小于0')
            return
          }
          if (Number(item.MinimumDiscount) > 100) {
            this.$set(item, 'MinimumDiscount', 100)
            this.$message.warning('不能大于100')
            return
          }
          if (Number(item.NumLowerLimit1) < 0) {
            this.$set(item, 'NumLowerLimit1', 1)
            this.$message.warning('不能小于0')
            return
          }
          if (Number(item.LowerLimitPrice1) < 0) {
            this.$set(item, 'LowerLimitPrice1', 1)
            this.$message.warning('不能小于0')
            return
          }
          if (Number(item.NumLowerLimit2) < 0) {
            this.$set(item, 'NumLowerLimit2', 1)
            this.$message.warning('不能小于0')
            return
          }

          if (Number(item.LowerLimitPrice2) < 0) {
            this.$set(item, 'LowerLimitPrice2', 1)
            this.$message.warning('不能小于0')
            return
          }
          if (Number(item.NumLowerLimit3) < 0) {
            this.$set(item, 'NumLowerLimit3', 1)
            this.$message.warning('不能小于0')
            return
          }
          if (Number(item.LowerLimitPrice3) < 0) {
            this.$set(item, 'LowerLimitPrice3', 1)
            this.$message.warning('不能小于0')
            return
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      columns,
      Id: '',
      QPLD_List: [],
      queryParam: {},
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => {
          this.pageSize = pageSize
        }
      },
      filters: {},
      sorter: { field: 'Id', order: 'desc' },
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },

      selectedRowKeys: [],
      data: [],
      visible: false,

      entity: {},
      rules: {
        ListName: [{ required: true, message: '未输入', trigger: 'blur' }],
        StartValidity: [{ required: true, message: '未输入', trigger: 'change' }],
        EndValidity: [{ required: true, message: '未输入', trigger: 'change' }]
      },
      title: ''
    }
  },
  methods: {
    disabledDate(current) {
      const startValue = this.entity.StartValidity
      if (startValue) {
        return startValue.valueOf() >= current.valueOf()
      } else {
        return current.valueOf() <= moment().subtract(1, 'days')
      }
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      if (this.Id) {
        this.$http
          .post('/QuotationManagement/Quot_PriceListMain/GetTheDataOfAll', {
            PageIndex: this.pagination.current,
            PageRows: this.pagination.pageSize,
            SortField: 'Id',
            SortType: 'desc',
            Search: {
              Condition: 'Id',
              Keyword: this.Id
            }
          })
          .then(res => {
            //console.log(res)
            if (res.Success) {
              if (res.Data.Total) {
                const pagination = { ...this.pagination }
                pagination.total = res.Data.Total
                this.pagination = pagination
              }
            } else {
              this.$message.error(res.Msg)
            }
          })
      }
    },
    addTable() {
      this.$refs.materialChoose.openChoose(null, this.data)
    },

    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    close() {
      this.visible = false
      this.data = []
      // this.entity.IsLadderPrice = false
    },
    handleChoose(a) {
      //console.log(a)

      var ar = []

      this.data.forEach(item => {
        //console.log(this.data)
        a.forEach((val, i) => {
          //console.log(val)
          if (item.ProductId == val.cInvCode) {
            ar.push(val)
            delete a[i]
          }
        })
      })
      //console.log(ar)

      if (ar.length == 0) {
        a.forEach(item => {
          //console.log(this.data)

          this.data.push({
            cInvCode: item.cInvCode,
            cInvName: item.cInvName,
            cInvStd: item.cInvStd,
            LowerLimitPrice1: 1,
            LowerLimitPrice2: 1,
            LowerLimitPrice3: 1
          })
        })
        //console.log(ar)
        // this.data = [...this.data, ...a]
      } else {
        this.$message.error('重复产品已筛选掉')
        a.forEach(item => {
          //console.log(item)
          this.data = [...this.data, item]
        })

        //console.log(a)
      }
    },
    init() {
      this.data = []
      this.entity = {}
      this.$set(this.entity, 'IsLadderPrice', false)
    },
    blur1(e, row) {
      if (row.LowerLimitPrice1) row.LowerLimitPrice1 = Number(row.LowerLimitPrice1).toFixed(2)
      // if (value) return Number(value).toFixed(2)
    },
    blur2(e, row) {
      if (row.LowerLimitPrice2) row.LowerLimitPrice2 = Number(row.LowerLimitPrice2).toFixed(2)
      // if (value) return Number(value).toFixed(2)
    },
    blur3(e, row) {
      if (row.LowerLimitPrice3) row.LowerLimitPrice3 = Number(row.LowerLimitPrice3).toFixed(2)
      // if (value) return Number(value).toFixed(2)
    },
    getDataList() {
      this.$http
        .post('/QuotationManagement/Quot_PriceListMain/GetTheDataOfAll', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'Id',
          SortType: 'desc',
          Search: {
            Condition: 'Id',
            Keyword: this.Id
          }
        })
        .then(res => {
          //console.log(res)
          if (res.Success) {
            this.entity = res.Data
            if (this.entity['StartValidity']) {
              this.entity['StartValidity'] = moment(this.entity['StartValidity'])
            }
            if (this.entity['EndValidity']) {
              this.entity['EndValidity'] = moment(this.entity['EndValidity'])
            }
            this.data = res.Data.QPLD_List
            //console.log(this.data)
            if (res.Data.Total) {
              const pagination = { ...this.pagination }
              pagination.total = res.Data.Total
              this.pagination = pagination
            }
          } else {
            this.$message.error(res.Msg)
          }
        })
    },
    handleDelete(ids, index) {
      if (ids[0]) {
        var thisObj = this
        this.$confirm({
          title: '确认删除吗?',
          onOk() {
            return new Promise((resolve, reject) => {
              thisObj.$http.post('/QuotationManagement/Quot_PriceListDetails/DeleteData', ids).then(resJson => {
                resolve()

                if (resJson.Success) {
                  thisObj.$message.success('操作成功!')

                  thisObj.getDataList()
                } else {
                  thisObj.$message.error(resJson.Msg)
                }
              })
            })
          }
        })
      } else {
        this.data.splice(index, 1)
        //console.log(123)
      }
    },
    openForm(id, title) {
      this.init()

      this.title = title
      if (id) {
        this.Id = id
        this.getDataList()
        // this.loading = true
        // this.$http.post('/QuotationManagement/Quot_PriceListMain/GetTheData', { id: id }).then(resJson => {
        //   this.loading = false
        //   this.entity = resJson.Data
        //   this.queryParam = { Id: this.id }
        // })
      }
      this.visible = true
    },
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }

        this.loading = true
        let a = this.data.some(item => {
          if (item.NumLowerLimit2) {
            return Number(item.NumLowerLimit2) <= item.NumLowerLimit1
          }
        })
        if (a) {
          this.$message.error('N2不能小于N1数量')
          return
        }
        let c = this.data.some(item => {
          if (item.NumLowerLimit3) {
            return Number(item.NumLowerLimit3) <= item.NumLowerLimit2
          }
        })
        if (c) {
          this.$message.error('N3不能小于N2数量')
          return
        }
        let MinimumDiscount = this.data.some(item => {
          return item.MinimumDiscount <= 0
        })

        if (MinimumDiscount) {
          this.$message.error('折扣不能为空')
          return
        }
        var entityData = { ...this.entity }
        var QPLD_List = [...this.data]
        this.QPLD_List = QPLD_List
        //console.log(this.QPLD_List)
        // this.QPLD_List.forEach(item => {
        //   item.ProductId = item.id
        // })
        entityData.QPLD_List = this.QPLD_List

        //console.log(entityData)
        this.$http.post('/QuotationManagement/Quot_PriceListMain/SaveData', entityData).then(resJson => {
          this.loading = false

          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.visible = false

            this.parentObj.getDataList()
          } else {
            this.$message.error(resJson.Msg)
          }
        })
      })
    }
  }
}
</script>
